var isIE = false;
var isFirefox = false;
var isSafari = false;
var isNetscape = false;
var isMozilla = false;
var isOther = false;

var isGridDirty = false;
var filesToUpload = new Array();
var filesUploaded = new Array();
var fileBeingUploaded = '';
var fileUploaded = '';
var timerFullUpload;
var timerIndividualUpload;
var uploadFilesComplete = false;

var dataValidated = false;
function SetGridDirty()
{
	isGridDirty = true;
}
function BrowserDetect()
{
	var browserVendor = navigator.appName;
	if (browserVendor.substr("Microsoft") >= 0)
		isIE = true;
	
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("firefox") != -1) 
		isFirefox = true;
	if (agt.indexOf("safari") != -1) 
		isSafari = true;
	if (agt.indexOf("msie") != -1) 
		isIE = true;
	if (agt.indexOf("netscape") != -1) 
		isNetscape = true;
	if (agt.indexOf("mozilla/5.0") != -1) 
		isMozilla = true;
	
	if (agt.indexOf('\/') != -1) 
	{
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') 
		{
			isOther = true; //navigator.userAgent.substr(0,agt.indexOf('\/'));
		}
		else 
			isNetscape = true;
	} 
	else if (agt.indexOf(' ') != -1)
		isOther = true; //navigator.userAgent.substr(0,agt.indexOf(' '));
	else 
		isOther = true; //navigator.userAgent;

//alert('IE' + isIE + ' FF' + isFirefox + ' Safari' + isSafari + ' NN' + isNetscape + ' Moz' + isMozilla + ' Oth' + isOther);
}

//Get child nodes with the specified name
function GetByTagName(node, name)
{ 
	var childArray = new Array(); 
	for(var i=0; i<node.childNodes.length; i++)
	{ 
		if(node.childNodes[i].nodeName == name)
		{ 
			childArray[childArray.length] = node.childNodes[i]; 
		} 
	} 
	return childArray; 
} 

//Replacement for innerHTML
function SetInnerHTML(elementid, content)
{
	if (document.getElementById && !document.all)
	{
		rng = document.createRange();
		el = document.getElementById(elementid);
		rng.setStartBefore(el);
		htmlFrag = rng.createContextualFragment(content);
		while (el.hasChildNodes())
			el.removeChild(el.lastChild);
		el.appendChild(htmlFrag);
	}
}



function CloseWindowAndRefreshParent()
{
	window.opener.location.reload();
	window.close();
}

//If Electronic File is checked, then Hardcopy is unselected and the file browser control is enabled. 
//If electronic file is unchecked, then file browser control is disabled.
function ToggleControlsForElectronicFile(attachmentElectronic, attachmentHardCopy, attachedFile)
{ 
	isGridDirty = true;
	if (document.getElementById(attachmentElectronic).checked)
	{
		document.getElementById(attachmentHardCopy).checked = false;
		
		if (isIE) //IE
		{
			//document.frames(attachedFile).document.getElementById('fileUploader').setAttribute('disabled', false);
			document.frames(attachedFile).document.getElementById('fileUploader').style.display = 'block';
		}
		else if(isFirefox)//FireFox
		{
			//document.all(attachedFile).contentDocument.getElementById('fileUploader').disabled = false;
			document.all(attachedFile).contentDocument.getElementById('fileUploader').style.display = 'block';
		}
		else if(isSafari || isNetscape)
		{
			//document.getElementById(attachedFile).contentDocument.getElementById('fileUploader').setAttribute('disabled', false);
			document.getElementById(attachedFile).contentDocument.getElementById('fileUploader').style.display= 'block';
		}
	}
	else
	{
		if (isIE) //IE
		{
			//document.frames(attachedFile).document.getElementById('fileUploader').setAttribute('disabled', true);
			document.frames(attachedFile).document.getElementById('fileUploader').style.display = 'none';
		}
		else if(isFirefox)//FireFox
		{
			//document.all(attachedFile).contentDocument.getElementById('fileUploader').disabled = true;
			document.all(attachedFile).contentDocument.getElementById('fileUploader').style.display = 'none';
		}
		else if (isSafari || isNetscape)
		{
			//document.getElementById(attachedFile).contentDocument.getElementById('fileUploader').disabled = true;
			document.getElementById(attachedFile).contentDocument.getElementById('fileUploader').style.display= 'none';
		}
	}
	
}

//Version page - No frame
//If Electronic File is checked, then Hardcopy is unselected and the file browser control is enabled. 
//If electronic file is unchecked, then file browser control is disabled.
function ToggleControlsForVersionsElectronicFile(attachmentElectronic, attachmentHardCopy, attachedFile)
{ 
	if (document.getElementById(attachmentElectronic).checked)
	{
		document.getElementById(attachmentHardCopy).checked = false;
		//if (document.frames) //IE
		{
		//	document.getElementById(attachedFile).setAttribute('disabled', false);
		}
		//else if(document.all != "undefined")//FireFox
		{
			document.getElementById(attachedFile).disabled = false;
		}
	}
	else
	{
		//if (document.frames) //IE
		{
		//	document.frames(attachedFile).document.getElementById('fileUploader').setAttribute('disabled', true);
		}
		//else if(document.all != "undefined")//FireFox
		{
		//	document.all(attachedFile).contentDocument.getElementById('fileUploader').disabled = true;
		}
		document.getElementById(attachedFile).disabled = true;
	}
	
}


//If Hardcopy is checked, then electronic file is unchecked and the file browser control is disabled.
function ToggleControlsForHardCopy(attachmentHardCopy, attachmentElectronic, attachedFile)
{
	isGridDirty = true;
	if (document.getElementById(attachmentHardCopy).checked)
	{
		document.getElementById(attachmentElectronic).checked = false;
		if (isIE) //IE
		{
			//document.frames(attachedFile).document.getElementById('fileUploader').setAttribute('disabled', true);
			document.frames(attachedFile).document.getElementById('fileUploader').style.display = 'none';
		}
		else if(isFirefox)//FireFox
		{
			//document.all(attachedFile).contentDocument.getElementById('fileUploader').disabled = true;
			document.all(attachedFile).contentDocument.getElementById('fileUploader').style.display = 'none';
		}
		else if (isSafari || isNetscape)
		{
			//document.getElementById(attachedFile).contentDocument.getElementById('fileUploader').disabled = true;
			document.getElementById(attachedFile).contentDocument.getElementById('fileUploader').style.display= 'none';
		}
	}
	
}

//Version page - No frame
//If Hardcopy is checked, then electronic file is unchecked and the file browser control is disabled.
function ToggleControlsForVersionsHardCopy(attachmentHardCopy, attachmentElectronic, attachedFile)
{
	if (document.getElementById(attachmentHardCopy).checked)
	{
		document.getElementById(attachmentElectronic).checked = false;
		//if (document.frames) //IE
		{
		//	document.frames(attachedFile).document.getElementById('fileUploader').setAttribute('disabled', true);
		}
		//else if(document.all != "undefined")//FireFox
		{
		//	document.all(attachedFile).contentDocument.getElementById('fileUploader').disabled = true;
		}
		document.getElementById(attachedFile).disabled = true;
	}
	
}

//Adds a blank row to the grid.
function addNewAttachment_Click()
{
	isGridDirty = true;
	//check if date uploaded and view attachment columns are visible
	var isDateUploadedVisible = document.getElementById('dateUploadedColumnVisible').value; //hidden field

	var id;

	//var attachmentDetailsBody = document.getElementById('attachmentsDetail').childNodes('TBODY');
	var attachmentDetailsBody = GetByTagName(document.getElementById('attachmentsDetail'), 'TBODY');
	
	var attachmentsRowCount = document.getElementById('attachmentsRowCount'); //hidden field which holds the number of rows in the datagrid

	var rowIndex = (attachmentsRowCount.value - 1) + 2; //.value returns string and directly adding 1 would be essentially append 1 to the string.
	var colIndex = 0;
	
	attachmentsRowCount.value = rowIndex;
	var newRow = document.createElement('TR');
	
	if (rowIndex % 2 != 0)
		newRow.className = "DataGridItem";
	else
		newRow.className = "DataGridAlternatingItem";
		
	newRow.setAttribute('title', 'NEWROW');
	newRow.setAttribute('id', 'NEWROW' + rowIndex); 
	
	var newColType = document.createElement('TD');
	id = "attachmentType" + rowIndex;
	//load attachment types from the hidden text field
	var attachmentTypesList = document.getElementById('attachmentTypesList');
	var arrayAttachmentTypes = attachmentTypesList.value.split("^");
	var innerHTML = '<select name="attachmentType" class="FlatDropDown" id="' + id + '" onChange="javascript:OnAattachmentTypeSelect(this)">'
	for (var i=0; i<arrayAttachmentTypes.length; ++i)
	{
		var textValue = arrayAttachmentTypes[i].split("|");
		innerHTML += '<option value="' + textValue[0] +'">' + textValue[1] + '</option>';
	}
			
	innerHTML += '</select>';
	newColType.innerHTML = innerHTML;
	
	newRow.appendChild(newColType);
	colIndex++;
	
	var newColTitle = document.createElement('TD');
	id = "attachmentTitle" + rowIndex;
	newColTitle.innerHTML = '<input name="attachmentTitle" type="text" class="FlatTextBox" id="' + id + '"  />';
	newRow.appendChild(newColTitle);
	colIndex++;
	
	var newColFormat = document.createElement('TD');
	id = "attachmentElectronic" + rowIndex;
	var attachedFileId = "attachedFile" + rowIndex;
	var attachmentHardCopyId = "attachmentHardCopy" + rowIndex;
	newColFormat.innerHTML = '<input name="attachmentElectronic" id="' + id + '" type="checkbox" onclick="javascript:ToggleControlsForElectronicFile(\'' + id + '\', \'' + attachmentHardCopyId + '\', \'' + attachedFileId + '\')" />' +
						'<label for="' + id + '">Electronic</label>&nbsp;&nbsp; ' +
						'<input name="attachmentHardCopy" id="' + attachmentHardCopyId + '" type="checkbox" onclick="javascript:ToggleControlsForHardCopy(\'' + attachmentHardCopyId + '\', \'' + id + '\', \'' + attachedFileId + '\')" />' +
						'<label for="' + attachmentHardCopyId + '">Hardcopy</label>';
	newRow.appendChild(newColFormat);
	colIndex++;
	
	var newColFile = document.createElement('TD');
	//newColFile.innerHTML = '<input name="' + attachedFileId + '" id="' + attachedFileId + '" type="file" class="FlatTextBox" disabled/>&nbsp;<span id="attachedFileName"></span>&nbsp;';
	newColFile.innerHTML = '<iFrame name="' + attachedFileId + '" id="' + attachedFileId + '" src="FileUploadPage.aspx" frameborder="no" scrolling="no" marginheight="0" marginwidth="0" disabled="disabled" ALLOWTRANSPARENCY="true" height="30"></iFrame>&nbsp;<span id="attachedFileName"></span>&nbsp;';
	newRow.appendChild(newColFile);
	colIndex++;
	
	var newColAmeNumber = document.createElement('TD');
	newRow.appendChild(newColAmeNumber);
	colIndex++;
	
	if (isDateUploadedVisible == 'true')
	{
		var newColDateUploaded = document.createElement('TD');
		newRow.appendChild(newColDateUploaded);
		colIndex++;
		
		var newColViewAttachment = document.createElement('TD');
		newRow.appendChild(newColViewAttachment);
		colIndex++;
	}
	
	var newColDelete = document.createElement('TD');
	newColDelete.setAttribute('align', 'center');
	id = "imgDelete" + rowIndex;
	newColDelete.innerHTML = '<input id="' + id + '" type="checkbox" name="attachmentMarkForDelete" />';
	newRow.appendChild(newColDelete);
	colIndex++;
	
	var newIncludeWithSubmission = document.createElement('TD');
	newIncludeWithSubmission.setAttribute('align', 'center');
	id = "flagIncludeWithSubmission" + rowIndex;
	newIncludeWithSubmission.innerHTML = '<input id="' + id + '" type="checkbox" name="attachmentIncludeWithSubmission" checked />';
	newIncludeWithSubmission.disabled = true;
//	newColTitle.attachEvent ("onChange",SetIncludeWithSubmission);
    
    if (colIndex <attachmentDetailsBody[0].firstChild.cells.length)
	    newRow.appendChild(newIncludeWithSubmission);
	    
	attachmentDetailsBody[0].appendChild(newRow);
}

//Removes a row from the grid
function RemoveRow(rowId)
{
	var attachmentDetailsBody = document.getElementById('attachmentsDetail').childNodes('TBODY');
	var rowToDelete = document.getElementById(rowId);
	attachmentDetailsBody.removeChild(rowToDelete);
}

//Checks if all the attachment title & type combinations are unique across the protocol 
//This method does the following for each row in the grid
//1. check if the title is empty, if so prompt the user to enter the title
//2. check if the title is modified (this will be evident if the title in the row being processed is 
//   looked up against the listedProtocolDocumentNames hidden field at the corresponding index)
//   listedProtocolDocumentNames contains the titles delimited by a '|' in the order they are displayed in the grid
//3. If the title is modified, then check if the modified title is found in the allProtocolDocumentNames hidden field.
//   If found, then prompt the user to change it.
//4. Prompts an app. message if file mode and the file itself are not selected
function ValidateData(allRows, typeIndex, titleIndex, fileFormatIndex, electronicFileIndex, hardCopyIndex, filePathIndex, markForDeleteIndex)
{
	//all the titles and types of attachments for the protocol delimited by '|' 
	var allProtocolDocumentNames = document.getElementById('allProtocolDocumentNames').value;
	//the titles and types of attachments listed in the grid on page load
	var listedProtocolDocumentNames = document.getElementById('listedProtocolDocumentNames').value;
	
	var listedNames = listedProtocolDocumentNames.split("|");
	
	for (var j=1; j<allRows.length; ++j) //allRows has the header row of the grid, hence started j with 1
	{
		//var allCols = allRows[j].getElementsByTagName('TD');
		var allCols = GetByTagName(allRows[j],'TD');
		var markForDelete = GetByTagName(allCols[markForDeleteIndex], 'INPUT');
		//Do not validate, if the row is marked for deletion.
		//If the mark for delete checkbox is disabled, a check box is enclosed in a span element. Hence the check for the non-zero length of the markForDelete array.
		if (markForDelete.length>0 && markForDelete[0].checked)
		{
			continue;
		}
		//Type
		var attType;
		var types = allCols[typeIndex].getElementsByTagName('Select');
		if (types.length > 0)
		{
			var type = GetByTagName(types[0], 'OPTION');
			if (type.length > 0 && type[0].selected)
			{
				alert('Attachment type must be specified');
				return false;
			}
			for(var k=1; k<type.length; ++k)
			{
				if (type[k].selected)
				{
					attType = type[k].value;
					break;
				}
			}
		}
		else
		{
			attType = (allCols[typeIndex].getElementsByTagName('Input'))[0].value;
		}
		//Title
		var oTitle = GetByTagName(allCols[titleIndex], 'INPUT');
		var title;
		if (oTitle.length == 0)
		{
			oTitle = GetByTagName(allCols[titleIndex], 'A');
			title = oTitle[0].innerHTML;
		}
		else
		{
			title = oTitle[0].value;
		}
		if (title == '')
		{
			alert('Attachment title must be specified');
			return false;
		}
		if (title.match(/[|]/))
		{
			alert('Attachment title ' + title + ' contains invalid characters.');
			return false;
		}
		oFormat = allCols[fileFormatIndex].getElementsByTagName('INPUT'); //In firefox, if checkboxes are disabled, then the checkbox elements are surrounded by spans
		if (!(oFormat[electronicFileIndex].checked || oFormat[hardCopyIndex].checked))
		{
			alert('Attachment mode must be specified');
			return false;	
		}
		var typeAndTitle = trim(title) + '@' + attType;
		
		//if the title of the attachment is modified or the attachment is a new one, then verify if any other attachments have this title
		//listedNames length will be 1 in 2 cases: When there are no attachments listed and when there is 1 attachment listed and hence the check
		//for listedNames[0] against empty string
		if (j<=listedNames.length && listedNames[0] != '')
		{
			if (typeAndTitle != listedNames[j-1])  //check to see if the title has been modified -> compares with the original value
			{
				if (allProtocolDocumentNames.toLowerCase().indexOf('|' + typeAndTitle.toLowerCase() + '|') != -1)
				{
					alert('The attachment title \'' + title + '\' is already being used.  Please enter a different title in the attachment title text field of this row.');
					return false;
				}
			}
		}
		if (j>listedNames.length || listedNames[0] == '')  
		{
			if (allProtocolDocumentNames.toLowerCase().indexOf('|' + typeAndTitle.toLowerCase() + '|') != -1)
			{
				alert('The attachment title \'' + title + '\' is already being used.  Please enter a different title in the attachment title text field of this row.');
				return false;
			}
			
			//as the attachment is a new one, add it to the list of all protocol document names
			allProtocolDocumentNames = allProtocolDocumentNames + typeAndTitle + '|';
			
		}
		if (oFormat[electronicFileIndex].checked)
		{
			var filePath = allCols[filePathIndex].getElementsByTagName('IFRAME');
			if (filePath != null && filePath.length > 0)
			{
				var frameName = filePath[0].getAttribute('name');
				
				var documentFrames = window.frames;
				for(var i=0; i<documentFrames.length; ++i)
				{
					if (documentFrames[i].name == frameName)
					{
						if (documentFrames[i].document.getElementById("fileUploader").value == '')
						{
							alert('Select a file to upload');
							return false;
						}
						else if(! ValidateFileExtensions(documentFrames[i].document.getElementById("fileUploader").value))
						{
						    return false;
						}      
					}
				}				
				
			}
		}

	}
	return true;
}
//stores new rows(only) in a hidden field in the following format
//attachmenttype SEPERATOR_COLUMN title SEPERATOR_COLUMN electronicfile SEPERATOR_COLUMN hardcopy SEPERATOR_COLUMN filepath SEPERATOR_COLUMN delete SEPERATOR_COLUMN SEPERATOR_ROW
//any change in this layout should be reflected in the UpdateDetails() in the code-behind file
function SaveNewRowsInformation()
{
	var attachmentDetailsBody = GetByTagName(document.getElementById('attachmentsDetail'), 'TBODY');
	var allRows = GetByTagName(attachmentDetailsBody[0], 'TR');
	
	var allCols;
	var newRows = document.getElementById('newRowsData'); //hidden field
	newRows.value = "";
	var oCurrent;
	var oAttribute;
	var oType;
	var oTitle;
	var oFormat;
	var oFile;
	var oDelete;
	var controlName;
	//check if date uploaded and view attachment columns are visible
	var isDateUploadedVisible = document.getElementById('dateUploadedColumnVisible').value; //hidden field

	//var COLUMN_ID = ""; //COLUMN INVISIBLE
	var COLUMN_ATTACHMENTTYPE = "0";
	var COLUMN_TITLE = "1";
	var COLUMN_FILEFORMAT = "2";
	var INDEX_ELECTRONICFILE = "0";
	var INDEX_HARDCOPY = "1";
	var COLUMN_FILEPATH = "3";
	var COLUMN_AMENUMBER = "4";
	var COLUMN_DATEUPLOADED;
	var COLUMN_VIEWATTACHMENT;
	var COLUMN_DELETE;
	//var COLUMN_SYSTEMGENERATED = ""; //COLUMN INVISIBLE
	
	if (isDateUploadedVisible == 'true')
	{
		COLUMN_DATEUPLOADED = "5";
		COLUMN_VIEWATTACHMENT = "6";
		COLUMN_DELETE = "7";
	}
	else
	{
		COLUMN_DATEUPLOADED = "-1";
		COLUMN_VIEWATTACHMENT = "-1";
		COLUMN_DELETE = "5";
	}
	
	var SEPERATOR_COLUMN = "&nbsp;";
	var SEPERATOR_ROW = "&crlf;";

	if (!dataValidated && !ValidateData(allRows, COLUMN_ATTACHMENTTYPE, COLUMN_TITLE, COLUMN_FILEFORMAT, INDEX_ELECTRONICFILE, INDEX_HARDCOPY, COLUMN_FILEPATH, COLUMN_DELETE))
		return false;
	dataValidated = true;
			
	//When the upload button is clicked the first time, uploadFilesComplete is false. This function, then validates the data and starts
	//uploading the files, one after another. Upon successful completion of each file upload, the title of the file uploaded is added to 
	//the filesUploaded array. In the meanwhile, CheckAndReturn() keeps comparing the no. of files to be uploaded with the actual files uploaded
	//every 2 secs. Once all the files are uploaded, the uploadFilesComplete is set to true and this function is again called. 
	//All the new rows information is then gathered and the form is submitted.
	var documentFrames = window.frames;	
		
	if (documentFrames != null)
	{
		//count the number of frames 
		for(var i=0, j=0; i<documentFrames.length; ++i)
		{
			var frameName = documentFrames[i].name;
			if (documentFrames[i].document.getElementById("fileUploader").style.display != 'none')
			{
				if (documentFrames[i].document.getElementById("fileUploader").value != "")
				{
					//if frameName has an underscore then the row containing the frame is already bound. If not, the row is a new row
					if (frameName.lastIndexOf('_') > 0)
					{
						filesToUpload[j++] = document.getElementById(frameName.substr(0, frameName.lastIndexOf('_') + 1) + 'attachmentTypeCode').value
											+ '|' + document.getElementById(frameName.substr(0, frameName.lastIndexOf('_') + 1) + 'attachmentTitle').value;
					}
					else
					{
						var rowNum = frameName.substr(12); //12 - frame name starts with 'attachedFile'
						var titleControlId = "attachmentTitle" + rowNum; 
						var options = document.getElementById("attachmentType" + rowNum).getElementsByTagName('OPTION');
						var type;
						for (var k=0; k<options.length; ++k)
						{
							if (options[k].selected)
							{
								type = options[k].getAttribute('VALUE');
								break;
							}
						}
						filesToUpload[j++] = type + '|' + document.getElementById(titleControlId).value;
					}
				
				}
			}
		}
	}
	
	if (filesToUpload.length == 0)
		uploadFilesComplete = true;
	if (!uploadFilesComplete)
	{
		if (documentFrames != null)
		{
			InitiateUploading(documentFrames);
		}
		CheckAndReturn();
		return false;
	}
	else
	{
		for (var j=0; j<allRows.length; ++j)
		{
			oCurrent = allRows[j];
			oAttribute = oCurrent.title;
			if (oAttribute != null && oAttribute.indexOf('NEWROW') != -1)
			{
				allCols = GetByTagName(oCurrent, 'TD');
				
				//Type
				oType = allCols[COLUMN_ATTACHMENTTYPE].getElementsByTagName('SELECT')[0].getElementsByTagName('OPTION');
				for (var k=0; k<oType.length; ++k)
				{
					if (oType[k].selected)
					{
						newRows.value = newRows.value + oType[k].getAttribute('VALUE') + SEPERATOR_COLUMN;
						newRows.value = newRows.value + oType[k].innerHTML + SEPERATOR_COLUMN;
						break;
					}
				}
				//Title
				oTitle = allCols[COLUMN_TITLE].getElementsByTagName('INPUT');
				newRows.value = newRows.value + oTitle[0].value + SEPERATOR_COLUMN;
			
				//Electronic File
				oFormat = allCols[COLUMN_FILEFORMAT].getElementsByTagName('INPUT');
				newRows.value = newRows.value + oFormat[INDEX_ELECTRONICFILE].checked + SEPERATOR_COLUMN;
				
				//HardCopy
				newRows.value = newRows.value + oFormat[INDEX_HARDCOPY].checked + SEPERATOR_COLUMN;
				
				//TODO: no more required
				//File Path
				oFile = allCols[COLUMN_FILEPATH].getElementsByTagName('INPUT');
				if (oFile.length > 0)
				{
					newRows.value = newRows.value + oFile[0].getAttribute('value') + SEPERATOR_COLUMN;
					//InputFile Control Name
					controlName = oFile[0].name;
				}
				else
				{
					newRows.value = newRows.value + '' + SEPERATOR_COLUMN;
				}
				
				//Delete
				oDelete = allCols[COLUMN_DELETE].getElementsByTagName('INPUT');
				if (oDelete != null)
					newRows.value = newRows.value + oDelete[0].checked + SEPERATOR_COLUMN;
				else
					newRows.value = newRows.value + 'false' + SEPERATOR_COLUMN;
									
				//TODO: no more required
				//append file control name so as to get to the PostedFile
				newRows.value = newRows.value + controlName + SEPERATOR_COLUMN;
				
				newRows.value = newRows.value + SEPERATOR_ROW;
			}
		}
		return true;
	}
	
	
}

function InitiateUploading()
{
	var documentFrames = window.frames;
	//loop thru all the frames and upload files
	for(var i=0; i<documentFrames.length; ++i)
	{
		if (documentFrames[i].document.getElementById("fileUploader").style.display != 'none')
		{
			//get the title for the attachment & Set it to the hidden field in frame
			var frameName = documentFrames[i].name;

			//if frameName has an underscore then the row containing the frame is already bound. If not, the row is a new row
			if (frameName.lastIndexOf('_') > 0)
			{
				//type | title 
				documentFrames[i].document.getElementById("attachmentTypeNTitle").value =  document.getElementById(frameName.substr(0, frameName.lastIndexOf('_') + 1) + 'attachmentTypeCode').value
																								+ '|' + document.getElementById(frameName.substr(0, frameName.lastIndexOf('_') + 1) + 'attachmentTitle').value;
																						
			}
			else
			{
				var rowNum = frameName.substr(12); //12 - frame name starts with 'attachedFile'
				var titleControlId = "attachmentTitle" + rowNum; 
				var options = document.getElementById("attachmentType" + rowNum).getElementsByTagName('OPTION');
				var type;
				for (var k=0; k<options.length; ++k)
				{
					if (options[k].selected)
					{
						type = options[k].getAttribute('VALUE');
						break;
					}
				}
				documentFrames[i].document.getElementById("attachmentTypeNTitle").value = type + '|' + document.getElementById(titleControlId).value;
			}

			//check if the file is already uploaded
			var fileToUpload = documentFrames[i].document.getElementById("attachmentTypeNTitle").value;
			var j=0;
			for(; j<filesUploaded.length; ++j)
				if (filesUploaded[j] == fileToUpload)
					break;
			if (j<filesUploaded.length) //file is uploaded
				continue;
			
			documentFrames[i].document.forms[0].submit();

			fileBeingUploaded = fileToUpload;
			TrackUploadProgress();
			break;
		}
	}//end looping thru frames
}
function TrackUploadProgress()
{
	if (fileBeingUploaded == fileUploaded)
	{
		//alert('File uploaded: ' + fileUploaded)
		if (timerIndividualUpload != null)
			clearTimeout(timerIndividualUpload);
		InitiateUploading();
	}
	else
	{
		timerIndividualUpload = setTimeout("TrackUploadProgress();", 500);
	}
}
function CheckAndReturn()
{
	if (filesUploaded.length == filesToUpload.length)
	{
		if (timerFullUpload != null)
			clearTimeout(timerFullUpload);
		uploadFilesComplete = true;
		document.getElementById('updateUploadAttachments').click();
	}
	else
	{
		timerFullUpload = setTimeout("CheckAndReturn();", 500);
	}
}

//After the server saves the file, a script is registered to call this method.
function FileUploadComplete(typeAndTitle)
{
	filesUploaded[filesUploaded.length] = fileUploaded = typeAndTitle;
}

function adjustIFrameSize (iframeWindow) 
{
	if (iframeWindow.document.height) 
	{
		var iframeElement = document.getElementById(iframeWindow.name);
		iframeElement.style.height = iframeWindow.document.height + 'px';
		iframeElement.style.width = iframeWindow.document.width + 'px';
	}
	else if (document.all) 
	{
		var iframeElement = document.all[iframeWindow.name];
		if (iframeWindow.document.compatMode && iframeWindow.document.compatMode != 'BackCompat') 
		{
			iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 5 + 'px';
			iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth + 5 + 'px';
		}
		else 
		{
			iframeElement.style.height = iframeWindow.document.body.scrollHeight + 5 + 'px';
			iframeElement.style.width = iframeWindow.document.body.scrollWidth + 5 + 'px';
		}
	}
}

var attachmentDetailsBodyArray;
function OnAattachmentTypeSelect(obj)
{
    var selectedAttachmentType = obj.childNodes[obj.selectedIndex].text;
    var versionRegMsg = "A file with that Attachment type has already been attached. To add a new version, click on the Attachment title and click the 'add new version' button.";
    var versionSugMsg = "Are you sure you want to add a new form and not a new version?";
    var selectedObj = obj;
    var EnableControls = false;
    var DisableControls = true;
    
    if (attachmentDetailsBodyArray == null)
        attachmentDetailsBodyArray = getAttachmentDetailsArray();

    if (isVersionReq(selectedAttachmentType))
    {
        if (isVersionType(selectedAttachmentType))
        {
            alert(versionRegMsg);   
            ResetEditStatus(selectedObj, DisableControls, true);
            return;
        }
        ResetEditStatus(selectedObj, DisableControls, false);
       
    } 
    else if (isVersionSug(selectedAttachmentType))
    {
        if (isVersionType(selectedAttachmentType))
        {
            alert (versionSugMsg);                         
        }  
           
    } 
    
    attachmentDetailsBodyArray[attachmentDetailsBodyArray.length] = selectedAttachmentType;
    
    // update titles when user select an item from the attachment type list
    if (obj.parentNode.nextSibling.childNodes[0].disabled == true)
        ResetEditStatus (selectedObj, EnableControls);
    obj.parentNode.nextSibling.childNodes[0].value = selectedAttachmentType;

}

function ResetEditStatus (obj, controlStatus, emptyControl)
{
    var ElecFileID, HardCopyFileID, attachFileName;

    if (obj.value == "ATCHTYPE_PROTOCOLSUMMARY" || obj.value == "ATCHTYPE_DETPROT"  )
        obj.parentNode.nextSibling.childNodes[0].disabled = true;
    else
        obj.parentNode.nextSibling.childNodes[0].disabled = controlStatus;
        
    // reset title
    if (emptyControl) {
        obj.parentNode.nextSibling.childNodes[0].value = "";

        // reset file mode
        for (var i = 0; i < obj.parentNode.nextSibling.nextSibling.childNodes.length; i++) {
            if (obj.parentNode.nextSibling.nextSibling.childNodes[i].nodeName != "#text") {
                obj.parentNode.nextSibling.nextSibling.childNodes[i].checked = false;
                obj.parentNode.nextSibling.nextSibling.childNodes[i].disabled = controlStatus;
            }
        }

        // reset file
        ElecFileID = obj.parentNode.nextSibling.nextSibling.childNodes[0].id;
        attachFileName = obj.parentNode.nextSibling.nextSibling.nextSibling.childNodes[0].id;
        if (isIE)
            HardCopyFileID = obj.parentNode.nextSibling.nextSibling.childNodes[2].id;
        else //if (isFirefox)
            HardCopyFileID = obj.parentNode.nextSibling.nextSibling.childNodes[3].id;
        ToggleControlsForElectronicFile(ElecFileID, HardCopyFileID, attachFileName);
    }
}

function isVersionReq (obj) 
{
    var restrictedAttachmentTypes=new Array("Protocol Summary", "Detailed Protocol");
    for (var i=0;i<restrictedAttachmentTypes.length;i++){
        if (obj == restrictedAttachmentTypes[i])
            return true;
    }
    return false;
}

function isVersionSug (obj) 
{
    var SuggestededAttachmentTypes=new Array("Consent Form");
    for (var i=0;i<SuggestededAttachmentTypes.length;i++){
        if (obj == SuggestededAttachmentTypes[i])
            return true;
    }
    return false;
}

function isVersionType(typeObj)
{
    // check if the newly selected attachment type require versioning
//    var attachmentDetailsBody = GetByTagName(document.getElementById('attachmentsDetail'), 'TBODY')[0].childNodes;
    
    for (var i = 1; i < attachmentDetailsBodyArray.length; i++)
    {
            if (attachmentDetailsBodyArray[i] == typeObj)
            {               
                return true;
            }               
    } 

    return false;
}

function getAttachmentDetailsArray()
{   
    var attachmentDetailsBody = GetByTagName(document.getElementById('attachmentsDetail'), 'TBODY')[0].childNodes;
    var array = new Array(attachmentDetailsBody.length);
    for (var i = 1; i < attachmentDetailsBody.length-1; i++)
    {
        if (attachmentDetailsBody[i].childNodes[1] != null)
        {
            if (isIE)
            {
                array[i] = attachmentDetailsBody[i].childNodes[0].innerText.replace(/^\s+|\s+$/g, '');              
            }
            else //if (isFirefox)
            {
                array[i] = attachmentDetailsBody[i].childNodes[1].textContent.replace(/^\s+|\s+$/g, '');              
            }                
        }
    } 

    return array;
}

function ValidateFileExtensions(fieldvalue) {
    var extension = new Array(
            ".doc"
           ,".docx"
           ,".dot"
           ,".docm"
           ,".rtf"
           ,".xls"
           ,".xlsx"
           ,".ppt"
           ,".pptx"
           ,".pdf"
           ,".txt"
           ,".htm"
           ,".html"
           ,".mht"          
        );

    // if file extension in the range, it is allowed, otherwise, alert user
    var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
    thisext = thisext.toLowerCase();
    for(var i = 0; i < extension.length; i++) 
    {
	    if(thisext == extension[i]) 
	    { 
            return true;
        }
    }
    
    alert(thisext + " file format is not supported.");
    return false;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}